<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { usePagination } from '@sa/alova/client';
import { reactive } from 'vue';
import { useAppStore } from '@/store/modules/app';
import useCheckedColumns from '@/hooks/common/table/table-columns';
import useTableOperate from '@/views/manage/role/hook/table-operate';
import { $t } from '@/locales';
import { enableStatusRecord } from '@/constants/manage';
import { batchDeleteRole, deleteRole, paginateRole } from '@/service/api/manage';
import RoleOperateDrawer from './modules/role-operate-drawer.vue';
import PermissionDrawer from './modules/permission-drawer.vue';
import UserDrawer from './modules/user-drawer.vue';
import RoleSearch from './modules/role-search.vue';

const appStore = useAppStore();

const searchParams = reactive({
  // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
  // the value can not be undefined, otherwise the property in Form will not be reactive
  status: null,
  name: null,
  code: null
});

const { loading, data, refresh, page, pageSize, pageCount, send, remove } = usePagination(
  (pageNum, size) =>
    paginateRole({
      ...searchParams,
      pageNumber: pageNum,
      pageSize: size
    }),
  {
    data: ({ records }) => records,
    total: ({ total }) => total,

    // trigger reload when states in `searchParams` changed
    watchingStates: [searchParams],

    // debounce of `searchParams`
    debounce: [500]
  }
);
const getDataByPage = (newPage = 1) => {
  page.value = newPage;
  send(page.value, pageSize.value);
};

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  handleDelete,
  handleBatchDelete,
  checkedRowKeys,
  deleting,
  permissionDrawerVisible,
  editingPermissionData,
  handlePermissionAuth,
  userDrawerVisible,
  editingUserData,
  handleUserAuth
} = useTableOperate(data, {
  async delete(row) {
    await deleteRole(row.id as number);
    remove(row);
  },
  async batchDelete(rows) {
    await batchDeleteRole(rows.map(({ id }) => id as number));
    remove(...rows);
  }
});

function edit(id: number) {
  handleEdit(id);
}

function permissionAuth(id: number) {
  handlePermissionAuth(id);
}

function userAuth(id: number) {
  handleUserAuth(id);
}

const { columnChecks, columns } = useCheckedColumns<typeof paginateRole>(() => [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'name',
    title: $t('page.manage.role.roleName'),
    align: 'center',
    minWidth: 120
  },
  {
    key: 'code',
    title: $t('page.manage.role.roleCode'),
    align: 'center',
    minWidth: 120
  },
  {
    key: 'remark',
    title: $t('page.manage.role.roleDesc'),
    minWidth: 120
  },
  {
    key: 'status',
    title: $t('page.manage.role.roleStatus'),
    align: 'center',
    width: 100,
    render: row => {
      if (row.status === null) {
        return null;
      }

      const tagMap: Record<Common.EnableStatus, NaiveUI.ThemeColor> = {
        1: 'success',
        0: 'warning'
      };

      const label = $t(enableStatusRecord[row.status as Common.EnableStatus]);

      return <NTag type={tagMap[row.status as Common.EnableStatus]}>{label}</NTag>;
    }
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    width: 240,
    render: row => (
      <div class="flex-center gap-8px">
        <NButton type="primary" ghost size="small" onClick={() => edit(row.id as number)}>
          {$t('common.edit')}
        </NButton>
        <NButton type="primary" ghost size="small" onClick={() => permissionAuth(row.id as number)}>
          权限
        </NButton>
        <NButton type="primary" ghost size="small" onClick={() => userAuth(row.id as number)}>
          用户
        </NButton>
        <NPopconfirm
          onPositiveClick={() => handleDelete(row.id)}
          positiveButtonProps={{
            loading: deleting.value
          }}
        >
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    )
  }
]);
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <RoleSearch v-model:model="searchParams" @search="getDataByPage" />
    <NCard :title="$t('page.manage.role.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="refresh"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="{
          page,
          pageSize,
          showSizePicker: true,
          pageCount,
          pageSizes: [10, 15, 20, 25, 30],
          onUpdatePage(value) {
            page = value;
          },
          onUpdatePageSize(value) {
            pageSize = value;
          }
        }"
        class="sm:h-full"
      />
      <RoleOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="refresh"
      />
      <PermissionDrawer v-model:visible="permissionDrawerVisible" :row-data="editingPermissionData" />
      <UserDrawer v-model:visible="userDrawerVisible" :row-data="editingUserData" />
    </NCard>
  </div>
</template>

<style scoped></style>
